package com.tools.modules.table.service.impl;

import cn.hutool.core.util.StrUtil;
import com.tools.common.beans.constant.Constants;
import com.tools.common.utils.DateUtils;
import com.tools.generator.ConstantGen;
import com.tools.generator.config.ToolDataSource;
import com.tools.generator.entity.TableEntity;
import com.tools.generator.entity.TableFieldEntity;
import com.tools.generator.service.DataSourceService;
import com.tools.generator.service.TableService;
import com.tools.generator.utils.QueryUtils;
import com.tools.modules.table.help.TemplateUtil;
import com.tools.modules.table.service.GenFileService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * MD 文件
 *
 * @Author : ShangJY
 * @create 2024/6/2 13:50
 */
@Service("md")
public class MdFileServiceImpl implements GenFileService {


    @Autowired
    private TableService tableService;

    @Autowired
    private DataSourceService dataSource;

    @Override
    public File genFile(List<Long> tableIds) throws IOException {
        String lineSeparator = ConstantGen.LINE_SEPARATOR;
        StringBuilder buffer = new StringBuilder();
        buffer.append(lineSeparator);
        buffer.append(StrUtil.format("# {}","数据库字段详情"));
        buffer.append(lineSeparator);

        List<TableEntity> tableEntityList = tableService.selectTableByIds(tableIds);

        List<TableFieldEntity> fieldList = new ArrayList<>();
        tableEntityList.forEach(table->{
            ToolDataSource toolDataSource = dataSource.get(table.getDatasourceId());
            // 获取原生字段数据
            List<TableFieldEntity> tableFieldList = QueryUtils.getTableFieldList(toolDataSource, table.getId(), table.getTableName());
            fieldList.addAll(tableFieldList);
        });

        for (int i = 0; i < tableEntityList.size(); i++) {
            TableEntity tableEntity = tableEntityList.get(i);
            String tableName = tableEntity.getTableName();
            String tableComment = tableEntity.getTableComment();
            buffer.append(StrUtil.format("## {}.{}({}){}",(i+1),tableName,tableComment,lineSeparator));

            StringBuilder tableHead = new StringBuilder(lineSeparator);
            tableHead.append(StrUtil.format("|列名|数据类型|是否为空|主键|自增|默认值|备注|{}",lineSeparator));
            tableHead.append(StrUtil.format("|:----:|:----:|:----:|:----:|:----:|:----:|:----:|{}",lineSeparator));
            for (TableFieldEntity tableFieldEntity : fieldList) {
                if (tableEntity.getId().equals(tableFieldEntity.getTableId())) {
                    StringBuffer table = getStringBuffer(tableFieldEntity, lineSeparator);
                    tableHead.append(table);
                }
            }
            buffer.append(tableHead);
        }
        String name = DateUtils.getDateStr(DateUtils.DATE_YMDHS);
        File file = new File(ConstantGen.TEMP_DIR + ConstantGen.SEPARATOR+name+".md" );
        FileUtils.write(file,buffer.toString(),"utf-8");
        return file;
    }

    /**
     * 拼接表格数据
     * @param fieldEntity
     * @param lineSeparator
     * @return
     */
    private StringBuffer getStringBuffer(TableFieldEntity fieldEntity, String lineSeparator) {
        StringBuffer table = new StringBuffer();
        table.append(Constants.SYMBOL.VERTICAL);
        table.append(fieldEntity.getFieldName());
        table.append(Constants.SYMBOL.VERTICAL);
        table.append(StrUtil.format("{}({})",fieldEntity.getFieldType(),fieldEntity.getDataLength()));
        table.append(Constants.SYMBOL.VERTICAL);
        table.append(fieldEntity.isNullAble() ?"是":"");
        table.append(Constants.SYMBOL.VERTICAL);
        table.append(fieldEntity.isPrimaryPk()?"是":"");
        table.append(Constants.SYMBOL.VERTICAL);
        table.append(fieldEntity.isAutoIncrement()?"是":"");
        table.append(Constants.SYMBOL.VERTICAL);
        table.append(fieldEntity.getDefaultVal());
        table.append(Constants.SYMBOL.VERTICAL);
        table.append(fieldEntity.getFieldComment());
        table.append(Constants.SYMBOL.VERTICAL);
        table.append(lineSeparator);
        return table;
    }
}
